package com.zdya.combatdocuments.util;

import cn.hutool.core.io.FileUtil;
import com.aspose.words.Document;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

public class PdfUtil {

    public static void main(String[] args) {
        try {
            String inPath = "C:\\Users\\lenovo\\Downloads\\“双减”背景下，如何提高小学语文阅读教学有效性.docx";//需要转换的文件地址
            String outPath = "C:\\Users\\lenovo\\Desktop\\PDF";//pdf文件存储地址
            byte[] file = FileUtil.readBytes(inPath);
            long l1 = System.currentTimeMillis();
            InputStream inputStream = new ByteArrayInputStream(file);
            byte[] bytes = PdfUtil.word2pdf(inputStream);
            FileUtil.writeBytes(bytes, outPath + System.currentTimeMillis() + ".pdf");
            long l2 = System.currentTimeMillis();
            System.out.println("用时："+(l2-l1));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * word 转为 pdf 输出
     */
    public static byte[] word2pdf(InputStream inputStream) throws Exception {
        // 验证License
        if (!isWordLicense()) {
            return null;
        }
        Document doc = new Document(inputStream);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        doc.save(baos, com.aspose.words.SaveFormat.PDF);
        byte[] bytes = baos.toByteArray();
//        ByteArrayInputStream in = parse(baos);
        return bytes;

    }

    public static String word2pdf(String inPath, String outPath) {
        // 验证License
        if (!isWordLicense()) {
            return null;
        }
        FileOutputStream os = null;
        try {
            String path = outPath.substring(0, outPath.lastIndexOf(File.separator));
            File file = new File(path);
            // 创建文件夹
            if (!file.exists()) {
                file.mkdirs();
            }
            // 新建一个空白pdf文档
            file = new File(outPath);
            os = new FileOutputStream(file);
            // Address是将要被转化的word文档
            Document doc = new Document(inPath);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            doc.save(os, com.aspose.words.SaveFormat.PDF);
            os.close();
        } catch (Exception e) {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }
        return outPath;
    }


    /**
     * 验证 Aspose.word 组件是否授权
     * 无授权的文件有水印和试用标记
     */
    public static boolean isWordLicense() {
        boolean result = false;
        try {
            // 避免文件遗漏
            String licensexml = "<License>\n" +
                "<Data>\n" +
                "<Products>\n" +
                "<Product>Aspose.Total for Java</Product>\n" +
                "<Product>Aspose.Words for Java</Product>\n" +
                "</Products>\n" +
                "<EditionType>Enterprise</EditionType>\n" +
                "<SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                "<LicenseExpiry>20991231</LicenseExpiry>\n" +
                "<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                "</Data>\n" +
                "<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                "</License>";
            InputStream inputStream = new ByteArrayInputStream(licensexml.getBytes());
            com.aspose.words.License license = new com.aspose.words.License();
            license.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * OutputStream 转 InputStream
     */
    public static ByteArrayInputStream parse(OutputStream out) {
        ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
        ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        return swapStream;
    }

    /**
     * InputStream 转 File
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception {
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
        if (file.exists()) {
            return file;
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }

    /**
     * 根据网络地址获取 File 对象
     */
    public static File getFile(String url) throws Exception {
        String suffix = url.substring(url.lastIndexOf("."));
        HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
        httpUrl.connect();
        return PdfUtil.inputStreamToFile(httpUrl.getInputStream(), UUID.randomUUID().toString() + suffix);
    }

    public static Map<String, String> readPdfGetInfo(byte[] pdf) {
        Map<String, String> map = new HashMap();
        List<String> list = new ArrayList<>();
        try {
            PdfReader reader = new PdfReader(pdf);
            int pageNum = reader.getNumberOfPages();
            for (int i = 1; i <= pageNum; i++) {
                list.add(PdfTextExtractor.getTextFromPage(reader, i));
            }
            boolean classificationNo = false;
            boolean author = false;
            boolean description = false;
            boolean keywords = false;

            for (String str : list) {
                try {
                    str = str.replaceAll("\r\n", "\n");
                    String[] lines = str.split("\n");
                    for (int i = 0; i < lines.length; i++) {
                        String line = lines[i];
                        if (!classificationNo) {
                            if (line.contains("分类号")) {
//                            int fLIndex = line.indexOf("分类号");
                                String flh = line.split("分类号")[1];
                                char[] chars = flh.toCharArray();
                                boolean isLetter = false;
                                flh = "";
                                for (char ch : chars) {
                                    if ((Character.isLowerCase(ch) || Character.isUpperCase(ch)) && "".equals(flh)) {
                                        flh = flh + ch;
                                    } else {
                                        if (!" ".equals(ch + "") && !"".equals(flh)) {
                                            flh = flh + ch;
                                        } else {
                                            if (" ".equals(ch + "") && !"".equals(flh)) {
                                                break;
                                            }
                                        }
                                    }
                                }
                                map.put("classificationNo", flh);
                                classificationNo = true;
                            }
                        }
                        if (!author) {
                            if (line.contains("姓") && line.contains("名")) {
                                line = line.replaceAll(" ", "");
                                int fLIndex = line.indexOf("姓名");
                                String flh = line.substring(fLIndex + 3, line.length());
                                flh = flh.replaceAll(" ", "");
                                map.put("author", flh);
                                author = true;
                            }
                        }
                        if (!description) {
                            if (line.contains("摘") && line.contains("要")) {
                                String digest = "";
                                if (line.contains(":") || line.contains("：") || line.contains("【") || line.contains("[")) {
                                    line = line.replaceAll(" ", "");
                                    int i1 = line.indexOf("摘要");
                                    digest = line.substring(i1 + 3, line.length());
                                }
                                int n = 1;
                                do {
                                    digest = digest + "\n" + lines[i + n];
                                    n = n + 1;
                                } while (!lines[i + n].contains("关键词"));
                                map.put("description", digest);
                                description = true;
                                if (!author) {
                                    String line1 = lines[i - 1];
                                    if (!"".equals(line1)) {
                                        map.put("author", line1);
                                        author = true;
                                    } else {
                                        map.put("author", lines[i - 2]);
                                        author = true;
                                    }
                                }
                            }
                        }
                        if (!keywords) {
                            if (line.contains("关键词")) {
                                String[] split = line.split("关键词");
                                String keyWord = split[1].substring(1, split[1].length());
                                map.put("keywords", keyWord);
                                keywords = true;
//                            break;
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return map;
    }

}
